<template>
  <div>
    <el-dialog title="修改密码" v-model="passwordDialogVisible" width="30%">
      <el-form
        :model="passwordForm"
        ref="passwordFormRef"
        :rules="passwordRules"
        label-width="80px"
        :inline="false"
        size="default"
      >
        <el-form-item label="设置密码" prop="password">
          <el-input v-model="passwordForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input
            v-model="passwordForm.checkPassword"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span>
          <el-button @click="closePasswordDialog">取消</el-button>
          <el-button type="primary" @click="changePassword">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-card
      shadow="always"
      style="margin: 2px 5px"
      :body-style="{
        padding: '20px',
        height: 'calc(100vh - 100px)',
        'overflow-y': 'auto',
      }"
    >
      <el-form
        :model="userForm"
        :rules="userRules"
        ref="userFormRef"
        label-width="80px"
        :inline="false"
        size="large"
        class="user-form"
      >
        <el-upload
          method="put"
          name="avatar"
          :headers="uploadHeader"
          action="/sunny/sunnyUser/avatar"
          :auto-upload="true"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :before-upload="beforeUpload"
        >
          <template #trigger
            ><el-avatar
              class="avatar-container"
              :size="200"
              :src="userStore.avatar"
            ></el-avatar
          ></template>
        </el-upload>

        <el-form-item label="账号：">
          <span>{{ userForm.username }}</span>
        </el-form-item>
        <el-form-item label="密码：">
          <el-button
            type="primary"
            size="default"
            @click="passwordDialogVisible = true"
            >修改密码</el-button
          >
        </el-form-item>

        <el-form-item prop="nickname" label="昵称：">
          <el-input
            placeholder="请输入昵称"
            v-model="userForm.nickname"
          ></el-input>
        </el-form-item>
        <el-form-item prop="dept" label="部门：">
          <el-input
            placeholder="请输入所在部门"
            v-model="userForm.dept"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别：">
          <el-radio v-model="userForm.gender" label="男" size="large">
            男</el-radio
          >
          <el-radio v-model="userForm.gender" label="女" size="large">
            女</el-radio
          >
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="saveUser">确认保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { localStorage } from "@/api/storage";
import { updatePasswordApi, updateUserApi } from "@/api/sunnyuser";
import { useUserStore } from "@/stores/userStore";
import type { SunnyResponse } from "@/types/sunnyResp";
import {
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadInstance,
  type UploadRawFile,
} from "element-plus";
import { ref, reactive,onMounted } from "vue";
const userStore = useUserStore();
const userFormRef = ref<FormInstance>();
//深拷贝，避免未提交的修改影响其它组件
const userForm = ref({ ...userStore.sunnyUser });
const userRules = ref<FormRules>({
  nickname: [
    { required: true, message: "请填写昵称", trigger: "blur" },
    { min: 1, max: 36, message: "昵称长度请控制在3到36位", trigger: "blur" },
  ],
  dept: [
    { min: 1, max: 10, message: "部门名称长度在10位以内", trigger: "blur" },
  ],
});

onMounted(() => {
  userStore.getUser().then(() => {
    userForm.value = { ...userStore.sunnyUser };
  });
});

function saveUser() {
  console.log(userForm.value);
  if (!userFormRef.value) return;
  userFormRef.value.validate((valid) => {
    if (valid) {
      updateUserApi(userForm.value).then(() => {
        ElMessage.success("修改用户信息成功！");
        userStore.getUser();
      });
    } else {
      ElMessage.error("请按照提示修改用户信息");
    }
  });
}

//密码修改弹窗
const passwordDialogVisible = ref(false);
//密码和确认密码
const passwordForm = reactive({ password: "", checkPassword: "" });
const passwordFormRef = ref<FormInstance>();
//自定义的校验规则
const passwordRules = ref<FormRules>({
  password: [{ validator: validatePass, trigger: "blur" }],
  checkPassword: [{ validator: validateCheckPass, trigger: "blur" }],
});

//密码校验规则
function validatePass(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请输入密码！"));
  } else {
    if (value.length < 3 || value.length > 18) {
      callback(new Error("密码请限制在3到18位之间"));
    }
    //如果确认密码已经输入了，要验证和确认密码是否一致。
    if (passwordForm.checkPassword !== "") {
      if (!passwordFormRef.value) return;
      passwordFormRef.value.validateField("checkPassword", () => null);
    }
    callback();
  }
}

function validateCheckPass(rule: any, value: any, callback: any) {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== passwordForm.password) {
    //验证确认密码是否等于输入的密码
    callback(new Error("两次输入的密码不匹配！"));
  } else {
    callback();
  }
}

//关闭密码输入窗并重置
function closePasswordDialog() {
  passwordDialogVisible.value = false;
  if (!passwordFormRef.value) return;
  //清理校验状态和已经输入的字段信息。
  passwordFormRef.value.resetFields();
  passwordFormRef.value.clearValidate();
}

function changePassword() {
  if (!passwordFormRef.value) return;

  passwordFormRef.value.validate((valid) => {
    if (valid) {
      updatePasswordApi({
        username: userForm.value.username,
        password: passwordForm.password,
      }).then(() => {
        ElMessage.success("修改密码成功");
        //可以考虑补充退出登录回到登录界面用新密码登录
      });
      closePasswordDialog();
    } else {
      //校验失败不重置窗口
      ElMessage.error("请检查两次输入的密码");
    }
  });
}

//头像上传
const uploadHeader = { Authorization: localStorage.get("token") };
//其实在succes中包含的是返回状态码为200
function uploadSuccess(response: SunnyResponse) {
  console.log(response.msg);
  if (response.code === 1000) {
    //重新从服务器获取数据，更新store中的存储，同时也会触发avatarurl的更新，让头像能够实时刷新。
    userStore.getUser();
  } else {
    ElMessage.error(response.msg);
  }
}

//当上传失败出现的是其它返回状态码的时候，回调这个函数。
function uploadError(error: Error) {
  ElMessage.error(error.message);
}

//判断文件是图片格式，且大小不超过1M
function beforeUpload(rawFile: UploadRawFile) {
  if (
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/png" &&
    rawFile.type !== "image/gif"
  ) {
    ElMessage.error("头像必须是图片!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error("头像图片大小请不要超过1M");
    return false;
  }
  return true;
}
</script>

<style scoped>
.user-form {
  width: 60vw;
  position: relative;
  margin: 0 auto;
  overflow: hidden;
}

.avatar-container {
  margin: 0 calc(30vw - 180px);
}
</style>
